<template>
  <div class="attributeManage">
    <div class="crumbs">
      <header class="crumbs_arr_box">
        <span>属性管理</span>
      </header>
    </div>
    <div class="card_table">
      <!-- 表格头部控件 -->
      <header>
        <!-- 左侧查询控件 -->
        <span>
          <el-input
            clearable
            size="small"
            v-model="table_config.propertyId"
            class="sel_inp"
            placeholder="请输入内容"
          >
            <template slot="prepend">属性名称</template>
            <el-button @click="search" slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <el-input
            clearable
            size="small"
            v-model="table_config.propertyName"
            class="sel_inp"
            placeholder="请输入内容"
          >
            <template slot="prepend">显示名称</template>
            <el-button @click="search" slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <el-select
            @change="search"
            v-model="table_config.productCode"
            class="sel_head"
            size="small"
            filterable
            clearable
            placeholder="SDK厂商筛选"
          >
            <el-option
              v-for="item in productCode_arr"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            ></el-option>
          </el-select>
        </span>
        <!-- 右侧追加控件 -->
        <span>
          <el-button v-if="$currentRole>2" @click="show_form('添加属性', false, {})" type="primary" plain size="mini">添加属性</el-button>
        </span>
      </header>
      <!-- 表体区域 -->
      <section>
        <el-table
          v-loading="table_loading"
          :size="table_size"
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column prop="propertyId" label="属性名称" width="140"></el-table-column>
          <el-table-column prop="propertyName" label="显示名称" sortable></el-table-column>
          <el-table-column prop="scopeType" label="属性类型" sortable width="120">
            <template slot-scope="scope">
              {{
              scopeType_show(scope.row.scopeType)
              }}
            </template>
          </el-table-column>

          <el-table-column prop="dataType" label="数据类型" sortable width="120">
            <template slot-scope="scope">
              {{
              dataType_show(scope.row.dataType)
              }}
            </template>
          </el-table-column>

          <el-table-column prop="category" label="类别" sortable width="120">
            <template slot-scope="scope">
              {{
              category_show(scope.row.category)
              }}
            </template>
          </el-table-column>

          <el-table-column prop="verifyRule" label="是否字典类型" width="200">
            <template slot-scope="scope">
              {{
              scope.row.hasDict==1?'是':'否'
              }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="说明"></el-table-column>

          <el-table-column  v-if="$currentRole>2"  label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click="show_form('编辑属性', true, scope.row)"
                plain
                size="mini"
                type="text"
              >编辑</el-button>
              <el-button @click="property_disable(scope.row)" plain size="mini" type="text">禁用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </section>
      <!-- 分页控件 -->
      <footer>
        <el-pagination
          :current-page="table_config.currentPage"
          @size-change="handleSizeChange"
          @current-change="current_change"
          :page-sizes="[5, 10, 30, 50, 100]"
          :page-size="table_config.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total_page"
        ></el-pagination>
      </footer>
    </div>
    <!-- 抽屉区域 -->
    <el-drawer title :modal="false" :visible.sync="drawer_bool" :with-header="false">
      <div class="drawer_box">
        <header>
          <span class="til">{{ drawer_til }}</span>
          <i @click="drawer_bool = false" class="el-icon-close"></i>
        </header>
        <section>
          <div class="section_til">属性名</div>
          <div class="el_com">
            <el-input
              :disabled="drawer_obj.id?true:false"
              v-model="drawer_obj.propertyId"
              :size="table_size"
              class="el_inp"
              placeholder="请输入内容"
            ></el-input>
          </div>
          <div class="section_til">属性显示名</div>
          <div class="el_com">
            <el-input
              v-model="drawer_obj.propertyName"
              :size="table_size"
              class="el_inp"
              placeholder="请输入内容"
            ></el-input>
          </div>
          <div class="section_til">数据类型</div>
          <div class="el_com">
            <el-select
              v-model="drawer_obj.dataType"
              :size="table_size"
              class="el_inp"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dataType_arr"
                :key="item.code"
                :label="item.value"
                :value="item.code"
              ></el-option>
            </el-select>
          </div>
          <!-- 字符串数据类型下的验证规则 -->
          <template v-if="drawer_obj.dataType=='STRING'">
            <div class="section_til">字符类型长度范围</div>
            <div class="el_com rules_w">
              <el-input
                :step="1"
                type="number"
                :min="0"
                :size="table_size"
                v-model="drawer_obj.verifyRule.lowerValue"
                class="el_inp el_mini"
                placeholder="请输入内容"
              ></el-input>
              <span class="txt_mid">至</span>
              <el-input
                :step="1"
                :min="0"
                type="number"
                v-model="drawer_obj.verifyRule.upperValue"
                :size="table_size"
                class="el_inp el_mini"
                placeholder="请输入内容"
              ></el-input>
            </div>
          </template>
          <!-- 布尔数据类型下的验证规则 -->
          <template v-if="drawer_obj.dataType=='BOOL'"></template>
          <!-- 数值数据类型下的验证规则 -->
          <template v-if="drawer_obj.dataType=='NUMBER'">
            <div class="section_til">数值类型数值范围</div>
            <div class="el_com rules_w">
              <el-input
                type="number"
                :min="0"
                :size="table_size"
                class="el_inp el_mini"
                v-model="drawer_obj.verifyRule.lowerValue"
                placeholder="请输入内容"
              ></el-input>
              <span class="txt_mid">至</span>
              <el-input
                type="number"
                :min="0"
                v-model="drawer_obj.verifyRule.upperValue"
                :size="table_size"
                class="el_inp el_mini"
                placeholder="请输入内容"
              ></el-input>
            </div>
          </template>

          <div class="section_til">SDK产品编码</div>
          <div class="el_com">
            <el-select
              @change="get_data_value"
              :disabled="drawer_obj.id?true:false"
              v-model="drawer_obj.productCode"
              :size="table_size"
              class="el_inp"
              placeholder="请选择"
            >
              <el-option
                v-for="item in productCode_arr"
                :key="item.code"
                :label="item.value"
                :value="item.code"
              ></el-option>
            </el-select>
          </div>
          <div class="section_til">是否字典类型</div>
          <div class="el_com">
            <el-select
              filterable
              v-model="drawer_obj.hasDict"
              clearable
              :size="table_size"
              class="el_inp"
              placeholder="请选择"
            >
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="2"></el-option>
            </el-select>
          </div>
          <template v-if="drawer_obj.hasDict==1">
            <div class="section_til">
              字典类型枚举定义（ 以
              <b>英文逗号</b> 分割 ）
            </div>
            <div class="el_com">
              <el-input
                v-model="drawer_obj.emurations"
                :size="table_size"
                type="textarea"
                :rows="4"
                class="el_inp lang_txt"
                placeholder="请输入内容"
              ></el-input>
            </div>
          </template>

          <div class="section_til">属性类型</div>
          <div class="el_com">
            <el-select
              filterable
              :disabled="drawer_obj.id?true:false"
              v-model="drawer_obj.commonType"
              clearable
              :size="table_size"
              class="el_inp"
              placeholder="请选择"
            >
              <el-option label="预置属性" :value="1"></el-option>
              <el-option label="自定义属性" :value="2"></el-option>
            </el-select>
          </div>

          <!-- <div class="section_til">属性范围</div>
          <div class="el_com">
            <el-select
              v-model="drawer_obj.scopeType"
              :size="table_size"
              class="el_inp"
              placeholder="请选择"
            >
              <el-option
                v-for="item in scopeType_arr"
                :key="item.code"
                :label="item.value"
                :value="item.code"
              ></el-option>
            </el-select>
          </div> -->

          <div class="section_til">所属事件</div>
          <div class="el_com">
            <el-select
              v-model="drawer_obj.belongEvent"
              multiple
              :size="table_size"
              class="el_inp"
              placeholder="请选择"
            >
              <el-option
                v-for="item in data_value_list"
                :key="item.eventId"
                :label="item.eventName"
                :value="item.eventId"
              ></el-option>
            </el-select>
          </div>
          <div class="section_til">属性说明</div>
          <div class="el_com">
            <el-input
              v-model="drawer_obj.remark"
              :size="table_size"
              type="textarea"
              :rows="table_size == 'mini' ? 2 : table_size == 'small' ? 4 : 6"
              class="el_inp lang_txt"
              placeholder="请输入内容"
            ></el-input>
          </div>
        </section>
        <footer>
          <el-button
            class="btn"
            v-if="drawer_obj.id"
            @click="attr_edit"
            size="mini"
            type="primary"
          >修改</el-button>
          <el-button
            class="btn"
            v-if="!drawer_obj.id"
            @click="attr_add"
            size="mini"
            type="primary"
          >添加</el-button>
          <el-button class="btn" @click="drawer_bool = false" size="mini" type="primary" plain>取消</el-button>
        </footer>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import application from "@/utils/api/application.js";
export default {
  name: "attributeManage",
  components: {},
  data() {
    return {
      table_loading: false,
      tableData: [],
      total_page: 0, // 表格数据总量
      category_arr: [], // 类别数组
      productCode_arr: [
        // {
        //   value: "网舟",
        //   code: "wz"
        // },
        // {
        //   value: "极光",
        //   code: "jg"
        // },
        {
          value: "电信",
          code: "dx"
        }
      ], // SDK产品编码数组
      table_config: {
        currentPage: 1,
        pageSize: 10,
        productCode: null,
        propertyName: null, // 显示名称
        propertyId: null
      }, // 表格查询配置对象
      table_size: "small",
      drawer_bool: false, // 抽屉开关变量
      drawer_til: null,
      rules: null,
      data_value_list: [], // 属性值列表
      drawer_obj: {
        id: null,
        belongEvent: [], // 属性值数组
        propertyId: null, //属性名称
        productCode: null, // SDK产品编码
        propertyName: null, //属性显示名称
        scopeType: null, //属性类别键值
        dataType: null, //数据类型
        category: null, // 类别
        remark: null, // 属性描述
        hasDict: null, // 是否字典类型
        attributeType: null, // 属性类别
        commonType: null, // 属性类型
        emurations: "", // 字典类型枚举定义
        verifyRule: {
          upperValue: 0, // 数值上限
          lowerValue: 0 // 数值下限
        } // 验证规则
      }, // 抽屉弹窗存储大对象
      dataType_arr: [], // 数据类型选项组
      scopeType_arr: [] // 属性类型选项组
    };
  },
  watch: {
    drawer_obj: {
      handler(newValue) {
        try {
          console.log(newValue);
        } catch (err) {
          console.log(err, "错误");
        }
      },
      deep: true
    }
  },
  computed: {},
  methods: {
    // 属性类型判断
    scopeType_show(key) {
      let str = "未知";
      switch (key) {
        case 1:
          str = "全局";
          break;
        case 2:
          str = "事件";
          break;
        case 3:
          str = "平台内置";
          break;
        case 4:
          str = "web";
          break;
        case 5:
          str = "客户端";
          break;
        case 6:
          str = "android";
          break;
        case 7:
          str = "ios";
          break;
        default:
      }
      return str;
    },
    // 数据类型判断
    dataType_show(key) {
      let str = "未知";
      switch (key) {
        case "STRING":
          str = "字符串";
          break;
        case "BOOL":
          str = "布尔";
          break;
        case "NUMBER":
          str = "数值";
          break;
        default:
      }
      return str;
    },
    // 类别判断
    category_show(key) {
      let str = "未知";
      this.category_arr.map(_i => {
        if (_i.code == key) {
          str = _i.value;
        }
      });
      return str;
    },
    handleSizeChange(page) {
      this.table_config.pageSize = page;
      this.table_config.currentPage = 1;
      this.query();
    },
    // 页码切换函数
    current_change(page) {
      this.table_config.currentPage = page;
      this.query();
    },
    // 添加属性和编辑属性触发函数
    show_form(key, bool, obj) {
      this.drawer_til = key;
      // 编辑属性
      if (bool) {
        let pd = {};
        if (obj.verifyRule) {
          pd = {
            upperValue: Number(obj.verifyRule.upperValue), // 数值上限
            lowerValue: Number(obj.verifyRule.lowerValue) // 数值下限
          };
        } else {
          pd = {
            upperValue: 0, // 数值上限
            lowerValue: 0 // 数值下限
          };
        }
        let _arr = [];

        obj.belongEvent.map(_i => {
          _arr.push(_i.eventId);
        });

        let str = "";
        if (Array.isArray(obj.emurations)) {
          str = obj.emurations.join(",");
        }
        this.drawer_obj = {
          emurations: str,
          id: obj.id,
          hasDict: obj.hasDict,
          commonType: obj.commonType ? obj.commonType : 1,
          attributeType: obj.attributeType, //属性类别
          propertyId: obj.propertyId, //属性名称
          productCode: obj.productCode, // SDK产品编码
          propertyName: obj.propertyName, //属性显示名称
          scopeType: obj.scopeType, //属性类别键值
          belongEvent: _arr, //  属性类别数值 多选
          dataType: obj.dataType, //数据类型
          category: obj.category, // 类别
          remark: obj.remark, // 属性描述
          verifyRule: pd
        };
      } else {
        // 添加属性
        this.drawer_obj = {
          id: null,
          hasDict: null,
          emurations: "",
          belongEvent: [], // 属性值数组
          propertyId: null, //属性名称
          productCode: "wz", // SDK产品编码
          propertyName: null, //属性显示名称
          scopeType: this.scopeType_arr[0] ? this.scopeType_arr[0].code : null, //属性类别键值
          dataType: this.dataType_arr[0] ? this.dataType_arr[0].code : null, //数据类型
          attributeType: null, //属性类别
          commonType: 1,
          category: this.category_arr[0] ? this.category_arr[0].code : null, // 类别
          remark: null, // 属性描述
          verifyRule: {
            upperValue: 0, // 数值上限
            lowerValue: 0 // 数值下限
          } // 验证规则
        };
      }
      this.drawer_bool = true;
      this.get_data_value();
    },
    // 查询点击函数
    search() {
      this.table_config.currentPage = 1;
      this.query();
    },
    // 数据请求函数
    async query() {
      this.table_loading = true;
      let res = await application.property_list(this.table_config);
      this.table_loading = false;

      if (res&&res.success) {
        this.total_page = res.value.total;
        this.table_config.currentPage = res.value.currentPage;
        this.table_config.pageSize = res.value.pageSize;
        this.tableData = res.value.list;
      }
    },
    // 获取数据类型函数  属性类型键值
    async get_data_list(type) {
      let res = await application.event_prefabricated({
        type
      });
      if (!res||!res.success) {
        return;
      }
      if (type == "dataType") {
        this.dataType_arr = res.value.list;
      }
      if (type == "scopeType") {
        let _arr = [];
        res.value.list.map(_i => {
          let item = _i;
          item.code = Number(item.code);
          _arr.push(item);
        });
        this.scopeType_arr = _arr;
      }
      if (type == "category") {
        this.category_arr = res.value.list;
      }
    },
    // 获取属性值列表
    async get_data_value() {
      this.data_value_list = [];
      if(!this.drawer_obj.id){
        this.drawer_obj.belongEvent = []
      }

      let res = await application.event_list({
        productCode:this.drawer_obj.productCode?this.drawer_obj.productCode:null,
        eventId: null,
        currentPage: 1,
        pageSize: 9999
      });
      
      if (res&&res.success) {
        this.data_value_list = res.value.list;
      }
    },
    //去掉左边的空白
    trimLeft(s) {
      if (s == null) {
        return "";
      }
      var whitespace = new String(" \t\n\r");
      var str = new String(s);
      if (whitespace.indexOf(str.charAt(0)) != -1) {
        var j = 0,
          i = str.length;
        while (j < i && whitespace.indexOf(str.charAt(j)) != -1) {
          j++;
        }
        str = str.substring(j, i);
      }
      return str;
    },
    trimRight(s) {
      if (s == null) return "";
      var whitespace = new String(" \t\n\r");
      var str = new String(s);
      if (whitespace.indexOf(str.charAt(str.length - 1)) != -1) {
        var i = str.length - 1;
        while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1) {
          i--;
        }
        str = str.substring(0, i + 1);
      }
      return str;
    },

    // 校验函数
    checkRules() {
      let str = "";
      // 字符串数据类型
      let bool = true;
      if (this.drawer_obj.dataType == "STRING") {
        if (
          parseInt(this.drawer_obj.verifyRule.upperValue) !=
            this.drawer_obj.verifyRule.upperValue ||
          parseInt(this.drawer_obj.verifyRule.lowerValue) !=
            this.drawer_obj.verifyRule.lowerValue
        ) {
          bool = false;
          str = "字符类型不可为小数";
        }
        if (
          parseInt(this.drawer_obj.verifyRule.lowerValue) >
          parseInt(this.drawer_obj.verifyRule.upperValue)
        ) {
          bool = false;
          str = "限制区间异常";
        }
      }
      // 布尔数据类型
      if (this.drawer_obj.dataType == "BOOL") {
        this.drawer_obj.verifyRule.upperValue = null;
        this.drawer_obj.verifyRule.lowerValue = null;
      }
      // 数值数据类型
      if (this.drawer_obj.dataType == "NUMBER") {
        if (
          Number(this.drawer_obj.verifyRule.lowerValue) >
          Number(this.drawer_obj.verifyRule.upperValue)
        ) {
          bool = false;
          str = "限制区间异常";
        }
      }
      if (!bool) {
        this.$message({
          message: str,
          type: "warning"
        });
      }
      return bool;
    },

    // 编辑添加前，对抽屉对象进行数据整合
    drawer_obj_change() {
      let _attr_arr = [];

      this.data_value_list.map(_i => {
        this.drawer_obj.belongEvent.map(_is => {
          if (_is == _i.eventId) {
            _attr_arr.push(_i);
          }
        });
      });
      // 对数据字典枚举进行转化
      let _arrEmurations = this.drawer_obj.emurations.split(",");
      let arrEmurations = [];
      _arrEmurations.map(_i => {
        let _pstr = this.trimLeft(this.trimRight(_i));
        if (_pstr !== "") {
          arrEmurations.push(_pstr);
        }
      });
      this.drawer_obj.verifyRule.lowerValue = Number(
        this.drawer_obj.verifyRule.lowerValue
      );
      this.drawer_obj.verifyRule.upperValue = Number(
        this.drawer_obj.verifyRule.upperValue
      );
      let obj = {
        hasDict: this.drawer_obj.hasDict, // 是否字典类型
        emurations: arrEmurations, // 字典枚举
        verifyRule: this.drawer_obj.verifyRule, // 验证规则
        id: this.drawer_obj.id,
        belongEvent: _attr_arr, // 属性值数组
        propertyId: this.drawer_obj.propertyId, //属性名称
        productCode: this.drawer_obj.productCode, // SDK产品编码
        propertyName: this.drawer_obj.propertyName, //属性显示名称
        scopeType: this.drawer_obj.scopeType, //属性类别键值
        dataType: this.drawer_obj.dataType, //数据类型
        commonType: this.drawer_obj.commonType, //属性类别
        category: this.drawer_obj.category, // 类别
        remark: this.drawer_obj.remark // 属性描述
      };
      return obj;
    },
    // 事件禁用函数
    async property_disable(obj) {
      this.table_loading = true;
      let res = await application.property_disable({
        id: obj.id
      });
      let len = this.tableData.length;
      if (res&&res.success) {
        this.$message({
          message: "禁用成功",
          type: "success"
        });
        if (len == 1 && this.table_config.currentPage > 1) {
          this.table_config.currentPage--;
        }
        this.query();
      } else {
        this.table_loading = false;
      }
    },
    // 编辑事件属性递交
    async attr_edit() {
      let result = this.checkRules();
      if (!result) {
        return;
      }
      let config = this.drawer_obj_change();
      this.table_loading = true;
      let res = await application.property_update(config);
      if (res&&res.success) {
        this.$message({
          message: "修改成功",
          type: "success"
        });
        this.query();
      }
      this.drawer_bool = false;
    },
    // 添加事件属性
    async attr_add() {
      let result = this.checkRules();
      if (!result) {
        return;
      }
      let config = this.drawer_obj_change();
      this.table_loading = true;
      let res = await application.property_add(config);
      if (res&&res.success) {
        this.$message({
          message: "添加成功",
          type: "success"
        });
        this.query();
      }
      this.drawer_bool = false;
    }
  },
  created() {
    this.query();
    this.get_data_list("scopeType");
    this.get_data_list("dataType");
    this.get_data_list("category");
  }
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}
// 抽屉壳子元素
.drawer_box {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  header {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    padding: 0 20px 0 10px;
    border-bottom: 1px solid #e4e7ed;
    .til {
      font-family: "Helvetica Neue", Helvetica, "PingFang SC",
        "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
      font-size: 14px;
      font-weight: 600;
      color: rgba($color: #303133, $alpha: 1);
    }
    i {
      font-size: 16px;
      font-weight: 600;
      transition: all 0.5s ease;
    }
    i:hover {
      transform: rotate(90deg);
      font-size: 20px;
      font-weight: 800 !important;
    }
  }
  section::-webkit-scrollbar {
    display: none;
  }
  section {
    position: absolute;
    left: 0;
    right: 0;
    top: 60px;
    bottom: 66px;
    padding: 0 0 30px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;
    overflow-y: scroll;
    .section_til {
      width: 100%;
      text-indent: 20px;
      height: 30px;
      line-height: 30px;
      text-align: left;
      color: #909399;
      font-size: 12px;
    }
    .el_com {
      width: 100%;
      padding: 6px 0 6px 30px;
      // height: 60px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .el_inp {
        width: 300px;
      }
      .lang_txt {
        width: 98%;
      }
      .lang {
        width: 70%;
        min-width: 400px;
      }
      .el_left {
        width: 180px;
        margin-right: 10px;
      }
      .el_mini {
        // width: 130px;
      }
      .txt_mid {
        padding: 0 12px;
      }
    }
    .rules_w {
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      .el_inp {
        width: 40%;
      }
    }
  }
  footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 58px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 0;
    border-top: 1px solid #e4e7ed;
    .btn {
      margin: 0 20px;
    }
  }
}
.attributeManage::-webkit-scrollbar {
  display: none;
}
.attributeManage {
  width: 98%;
  margin: 0 auto;
  height: 98.6%;
  overflow-y: scroll;
  .card_table {
    width: 99%;
    margin: 10px auto 10px;
    padding-bottom: 50px;
    position: relative;
    header {
      width: 99%;
      margin: 0 auto;
      box-sizing: border-box;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .sel_head {
        width: 290px;
        margin-right: 6px;
        margin-left: 0;
      }
      .sel_inp {
        width: 380px;
        margin-right: 14px;
      }
    }
    footer {
      position: absolute;
      width: 97%;
      height: 50px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      bottom: 0;
      left: 1%;
    }
    section {
      width: 98%;
      // max-height: 66vh;
      overflow-y: scroll;
      margin: 6px auto;
    }
    section::-webkit-scrollbar {
      width: 0 !important;
    }
    section {
      -ms-overflow-style: none;
    }
    section {
      overflow: -moz-scrollbars-none;
    }
  }
}
</style>
